package com.itany.mall.service.impl;

import java.util.List;

import com.itany.mall.dao.ProductDao;
import com.itany.mall.dao.ProductTypeDao;
import com.itany.mall.entity.Product;
import com.itany.mall.entity.ProductType;
import com.itany.mall.exception.ProductNameExistsException;
import com.itany.mall.exception.ProductNotFoundException;
import com.itany.mall.exception.ProductTypeNotFoundException;
import com.itany.mall.factory.Autowired;
import com.itany.mall.factory.Component;
import com.itany.mall.service.ProductService;
import com.itany.mall.vo.PageInfo;

@Component("productServiceImpl")
public class ProductServiceImpl implements ProductService {

	@Autowired
	private ProductTypeDao productTypeDao;

	@Autowired
	private ProductDao productDao;

	@Override
	public List<Product> findAll() {
		return productDao.selectAll();
	}

	@Override
	public void addProduct(String name, double price, long typeId)
			throws ProductNameExistsException, ProductTypeNotFoundException {
		Product check = productDao.selectByName(name);
		if (check != null) {
			throw new ProductNameExistsException();
		}

		ProductType type = productTypeDao.selectById(typeId);
		if (type == null) {
			throw new ProductTypeNotFoundException();
		}

		Product p = new Product().setName(name).setPrice(price).setType(type).setNum(0);
		productDao.insert(p);
	}

	@Override
	public Product findById(long productId) throws ProductNotFoundException {
		Product p = productDao.selectById(productId);
		if (p == null) {
			throw new ProductNotFoundException();
		}
		return p;
	}

	@Override
	public PageInfo<Product> findAll(int pageNo, int pageSize) {
		List<Product> list = productDao.findAll(pageNo, pageSize);
		int totalCount = productDao.selectTotalCount();
		PageInfo<Product> page = new PageInfo<Product>();
		page.setPageNo(pageNo);
		page.setPageSize(pageSize);
		page.setTotalCount(totalCount);
		page.setList(list);
		return page;
	}

}
